package com.qingyang.activemq;

import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;

/**
 * 发送队列消息-test
 *
 * @author xp
 * Created on 2018/2/6
 */
public class Producter {
    private static Logger log = LoggerFactory.getLogger(Producter.class);

    private static final String url = "tcp://192.168.0.162:61616";
    private static final String userName = "admin";
    private static final String password = "admin";
    private static final String QUEUE_NAME = "spring_queue_test";

    public static void main(String[] args) {
        Producter sndMsg = new Producter();
        try {
            sndMsg.sendMessage();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

    public void sendMessage() {
        // JMS 客户端到JMSProvider 的连接
        Connection connection = null;

        try {
            // 连接工厂，JMS 用它创建连接
            // 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);
            connection = (Connection) connectionFactory.createConnection();
            // 启动连接
            connection.start();
            //Session：发送或接收消息的线程
            // 获取session(参数1:是否支持事务,参数2:签收模式)
            Session session = (Session) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // 消息的目的地，消息发送到那个队列
            Destination destination = session.createQueue(QUEUE_NAME);
            //MessageProducer：消息发送者（生产者）
            // 创建消息发送者
            MessageProducer producer = session.createProducer(destination);
            // 设置是否持久化
            //DeliveryMode.NON_PERSISTENT：不持久化
            //DeliveryMode.PERSISTENT：持久化
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);

            String msg = "";
            //{eventId: '', userId: '', rcNum: ''},

            // 设置消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("eventId", "1");
            jsonObject.put("userId", "24174");
            jsonObject.put("rcNum", "1");
            msg = JSONObject.toJSONString(jsonObject);

            TextMessage message = session.createTextMessage(msg);

            Thread.sleep(1000);
            // 发送消息到目的地方
            producer.send(message);

            // 释放连接
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
